package org.example.java.io;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * User: ZhangJuntao
 * Date: 14-3-19
 * Time: 下午7:33
 */
public class BigFileUtil {
  public static void main(String[] args) throws Exception {
//        removeLine("G:\\document\\data\\t_lucene_content.sql", 14);
//    read();
//    readLine();
//    readByNewIO();
    write();
  }

  public static void readByNewIO() throws Exception {
    int bufSize = 1024;
    byte[] bs = new byte[bufSize];
    ByteBuffer byteBuf = ByteBuffer.allocate(1024);
    int i = 50;
    FileChannel channel = new RandomAccessFile("G:\\document\\data\\test.xml", "r").getChannel();
    while (channel.read(byteBuf) != -1 && i-- > 0) {
      int size = byteBuf.position();
      byteBuf.rewind();
      byteBuf.get(bs);
      // 把文件当字符串处理，直接打印做为一个例子。
      System.out.println(new String(bs, 0, size));
      byteBuf.clear();
    }
  }


  public static void readLine() throws Exception {
    BufferedReader br = new BufferedReader(new FileReader(new File("G:\\document\\data\\test3.xml")));
    String s;
    int i = 50;
    //readLine 没有换行的大文件会抛堆溢出
    while ((s = br.readLine()) != null && i-- > 0) {
      System.out.println(s);
    }
  }

  public static void read() throws Exception {
    BufferedReader br = new BufferedReader(new FileReader(new File("G:\\document\\data\\test.xml")));
    int s;
    int i = 500;
    while ((s = br.read()) != -1 && i-- > 0) {
      System.out.print((char) s);
    }
  }


  private static void write() throws IOException {
    String path = "I:\\document\\data\\test0.xml";
    File file = new File(path);
    file.delete();
    file.createNewFile();
    try {
      // if file doesn't exists, then create it

      FileWriter fw = new FileWriter(file.getAbsoluteFile());
      BufferedWriter bw = new BufferedWriter(fw, 4024);
      bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<persons>\n");
      String[] com = new String[]{"Alulux-Office China", "AgSivo Oy", "sia Medialine (M) Sdn Bhd", "Asia Medialine (M) Sdn Bhd"};
      for (int i = 0; i < 1024*1024*1.5; i++) {
        bw.write("<person><user_id>" + i + "</user_id> <user_name>"+RandomUtil.randomAlphabetic(6)+"</user_name> <company_name>" + com[i % 4] + "</company_name> </person>\n");
      }
      bw.write("</persons>");
      bw.close();
      System.out.println("Done");
    } catch (IOException e) {
      e.printStackTrace();
    }


    //Todo use RandomAccessFile
    //    RandomAccessFile file = new RandomAccessFile(path, "rw");
//    file.writeUTF("<book sku=\"123_xaa\"><title>KingLear</title><author>WilliamShakespeare</author><price>6.95</price><category>classics</category></book>\n");
//    file.writeUTF("<book sku=\"123_xaa\"><title>KingLear</title><author>WilliamShakespeare</author><price>6.95</price><category>classics</category></book>\n");
//    file.close();
  }

  public static void removeLine(String path, int target) throws IOException {
    // Use a random access file
    RandomAccessFile file = new RandomAccessFile(path, "rw");
    int counter = 0;
    long offset = 0, length = 0;
    String str;

    while ((str = file.readLine()) != null) {
      counter++;
      System.out.println(str);
      if (counter == target) {
        offset = file.getFilePointer();
        break; // Found target line's offset
      }
    }

    length = file.getFilePointer() - offset;

    if (target > counter) {
      file.close();
      throw new IOException("No such line!");
    }

    byte[] buffer = new byte[4096];
    int read = -1; // will store byte reads from file.read()
    while ((read = file.read(buffer)) > -1) {
      file.seek(file.getFilePointer() - read - length);
      file.write(buffer, 0, read);
      file.seek(file.getFilePointer() + length);
    }
    file.setLength(file.length() - length); //truncate by length
    file.close();

    BufferedReader br = new BufferedReader(new FileReader(new File("G:\\document\\data\\t_lucene_content.sql")));
    String s;
    int i = 30;
    while ((s = br.readLine()) != null && i-- > 0) {
      System.out.println(s);
    }
  }
}
